// Copyright (c) 2024, the WwMusic project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

package com.springfairy.controller;

import com.springfairy.model.MoodDiary;
import com.springfairy.service.MoodDiaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;


import com.springfairy.model.MoodDiary;
import com.springfairy.service.MoodDiaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mood-diaries")
public class MoodDiaryController {
    @Autowired
    private MoodDiaryService moodDiaryService;

    // 写/更新日记（根据 userId + diaryDate）
    @PostMapping("/write")
    public ResponseEntity<MoodDiary> writeDiary(@RequestBody MoodDiary diary) {
        MoodDiary saved = moodDiaryService.writeDiary(diary);
        return ResponseEntity.ok(saved);
    }

    // 获取某个用户某天的日记
    @GetMapping("/user/{userId}/date/{diaryDate}")
    public ResponseEntity<MoodDiary> getDiaryByUserAndDate(
            @PathVariable Integer userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate diaryDate) {

        MoodDiary diary = moodDiaryService.getDiaryByUserAndDate(userId, diaryDate);
        return diary != null ? ResponseEntity.ok(diary) : ResponseEntity.notFound().build();
    }

    // 获取某个用户的全部日记（可扩展分页）
    @GetMapping("/user/{userId}/list")
    public ResponseEntity<List<MoodDiary>> getAllDiaries(@PathVariable Integer userId) {
        List<MoodDiary> list = moodDiaryService.getAllDiariesByUser(userId);
        return ResponseEntity.ok(list);
    }

    // 删除日记
    @PostMapping("/delete/{diaryId}")
    public ResponseEntity<Map<String, String>> deleteDiary(@PathVariable Integer diaryId) {
        boolean deleted = moodDiaryService.deleteDiary(diaryId);
        Map<String, String> response = new HashMap<>();
        if (deleted) {
            response.put("message", "日记删除成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("message", "日记不存在");
            return ResponseEntity.status(404).body(response);
        }
    }

    // 更新日记
    @PostMapping("/update/{diaryId}")
    public ResponseEntity<MoodDiary> updateDiary(@PathVariable Integer diaryId, @RequestBody MoodDiary diary) {
        diary.setId(diaryId);
        moodDiaryService.updateDiary(diary);
        return ResponseEntity.ok(diary);
    }
}


